﻿/*
Copyright (c) 2011 <a href="http://www.gutgames.com">James Craig</a>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.*/

#region Usings
using System.Data;
using System.Reflection;
using HaterAide.Interfaces;
using HaterAide.Mappings;
using Utilities.SQL;

#endregion

namespace HaterAide.SQL.SQLServer.Statements
{
    /// <summary>
    /// Selects an object based on an ID
    /// </summary>
    internal static class Select
    {
        #region Internal Static Functions

        internal static T Run<T>(string ConnectionString, object IDValue, IClassManager ClassManager,
            IMappingManager MappingManager, Session CurrentSession)
        {
            T ReturnValue = default(T);
            IClass ClassDefinition = ClassManager[typeof(T)];
            IAttributeMap ClassMapping = MappingManager.ClassMappings[typeof(T)];
            using (SQLHelper Helper = new SQLHelper("", ConnectionString, CommandType.StoredProcedure))
            {
                try
                {
                    Helper.Open();
                    ReturnValue = LoadMainClass<T>(ReturnValue, IDValue, ClassDefinition, ClassMapping, Helper);
                    ReturnValue = List.LoadLists<T>(ReturnValue, IDValue, ClassDefinition, ClassMapping, ClassManager, MappingManager, Helper);
                }
                catch { throw; }
                finally { Helper.Close(); }
            }
            if (ReturnValue != null)
            {
                ((IHaterAideObject)ReturnValue).ClearChanged0();
                ((IHaterAideObject)ReturnValue).Session0 = CurrentSession;
                ((IHaterAideObject)ReturnValue).Update0 = true;
            }
            return ReturnValue;
        }

        public static T LoadClass<T>(T ReturnValue, object IDValue, IClass ClassDefinition, IAttributeMap ClassMapping, SQLHelper Helper)
        {
            ReturnValue = (T)ClassDefinition.CreateInstance();
            for (int x = 0; x < ClassMapping.Properties.Count; ++x)
            {
                HaterAide.Mappings.Attribute Property = ClassMapping.Properties[x];
                if (Property.MappingType == AttributeType.Map)
                {
                    FieldInfo IDField = ReturnValue.GetType().GetField("_" + Property.Name + "IDDerived");
                    HaterAide.SQL.DataClasses.Column PropertyColumn = ((HaterAide.SQL.DataClasses.Column)Property.AssociatedTable);
                    IDField.SetValue(ReturnValue, Helper.GetParameter(PropertyColumn.Name, null));
                }
                else if (Property.MappingType == AttributeType.ManyToMany
                    || (Property.MappingType == AttributeType.ManyToOne
                        && Utilities.Reflection.Reflection.IsIEnumerable(Property.Type)))
                {
                    FieldInfo IDField = ReturnValue.GetType().GetField("_" + Property.Name + "IDDerived");
                    IDField.SetValue(ReturnValue, IDValue);
                }
                else if ((!Utilities.Reflection.Reflection.IsIEnumerable(Property.Type)
                            ||Utilities.Reflection.Reflection.IsOfType(Property.Type, typeof(string)))
                        && (Property.MappingType == AttributeType.Reference
                            || Property.MappingType == AttributeType.ID))
                {
                    HaterAide.SQL.DataClasses.Column PropertyColumn = ((HaterAide.SQL.DataClasses.Column)Property.AssociatedTable);
                    PropertyInfo TempPropertyInfo = ReturnValue.GetType().GetProperty(Property.Name);
                    TempPropertyInfo.SetValue(ReturnValue, Helper.GetParameter(PropertyColumn.Name, null), null);
                }
            }
            return ReturnValue;
        }

        #endregion

        #region Private Static Functions

        private static T LoadMainClass<T>(T ReturnValue, object IDValue, IClass ClassDefinition,
            IAttributeMap ClassMapping, SQLHelper Helper)
        {
            string StoredProcedure = "";
            if (ClassMapping.AssociatedTable.Name.EndsWith("_"))
            {
                StoredProcedure = ClassMapping.AssociatedTable.Name + "Select";
            }
            else
            {
                StoredProcedure = ClassMapping.AssociatedTable.Name + "_Select";
            }
            Helper.Command = StoredProcedure;
            HaterAide.SQL.DataClasses.Column IDColumn = ((HaterAide.SQL.DataClasses.Column)ClassMapping.IDProperties[0].AssociatedTable);
            if (IDColumn.DataType == SqlDbType.NVarChar)
            {
                Helper.AddParameter("@" + IDColumn.Name, (string)IDValue, IDColumn.Length);
            }
            else
            {
                Helper.AddParameter("@" + IDColumn.Name, IDValue, IDColumn.DataType);
            }
            Helper.ExecuteReader();
            if (Helper.Read())
            {
                ReturnValue = LoadClass<T>(ReturnValue, IDValue, ClassDefinition, ClassMapping, Helper);
            }
            return ReturnValue;
        }

        #endregion
    }
}